﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GiaoTrinhEPU.Repositories.Interfaces;
using GiaoTrinhEPU.Caching;
using GiaoTrinhEPU.Repositories.DataModels;
namespace GiaoTrinhEPU.Repositories.Repositories
{
    public class AuthorRepository : BaseRepository, IAuthorRepository
    {
        public AuthorRepository() : base() { }
        public AuthorRepository(ICacheProvider cacheProvider) : base(cacheProvider) { }

        /// <summary>
        /// Clear cache of all banks
        /// </summary>
        public void ClearCache()
        {
            Cache.Invalidate("authors");
        }

        /// <summary>
        /// Clear cache of the author
        /// </summary>
        /// <param name="key"></param>
        public void ClearCache(String key)
        {
            Cache.Invalidate("author-" + key);
        }
        /// <summary>
        /// Create a new bank
        /// </summary>
        /// <param name="item"></param>
        public void CreateAuthor(Author item)
        {
            try
            {
                using (var db = new ThuVienEPUDataContext())
                {
                    db.Authors.InsertOnSubmit(item);
                    db.SubmitChanges();
                }
            }
            catch (Exception ex)
            {
                Logger.Writer.Write(ex.Message, ex.Source);
            }
        }

        // <summary>
        /// Update Author
        /// </summary>
        /// <param name="item"></param>
        public void UpdateAuthor(Author item)
        {
            try
            {
                using (var db = new ThuVienEPUDataContext())
                {
                    var author = db.Authors.Single(a => a.Id.Equals(item.Id));
                    author.Id = item.Id;
                    author.Name = item.Name;
                    author.DepartmentId = item.DepartmentId;
                    author.Description = item.Description;
                    db.SubmitChanges();
                }
            }
            catch (Exception ex)
            {
                Logger.Writer.Write(ex.Message, ex.Source);
            }
        }
        /// <summary>
        /// Delete a Author
        /// </summary>
        /// <param name="id"></param>
        public void DeleteAuthor(int id)
        {
            try
            {
                using (var db = new ThuVienEPUDataContext())
                {
                    var author = db.Authors.Single(a => a.Id.Equals(id));
                    db.Authors.DeleteOnSubmit(author);
                    db.SubmitChanges();
                }
            }
            catch (Exception ex)
            {
                Logger.Writer.Write(ex.Message, ex.Source);
            }
        }
        /// <summary>
        /// List all Author in database, order by Author's name
        /// </summary>
        /// <returns></returns>
        public IEnumerable<AuthorModel> ListAuthors(bool cacheEnabled = true)
        {
            if (cacheEnabled == true)
            {
                // if it's not in the cache, we need to read it form the repository// First, check the cache
                IEnumerable<AuthorModel> authorData = Cache.Get("authors") as IEnumerable<AuthorModel>;

                // if it's not in the cache, we need to read it form the repository
                if (authorData == null)
                {
                    //Get the repository data
                    try
                    {
                        using (var db = new ThuVienEPUDataContext())
                        {
                            authorData = (from x in db.Authors
                                          join y in db.Departments
                                          on x.DepartmentId equals y.Id
                                          select new AuthorModel
                                          {
                                              Id = x.Id,
                                              Name = x.Name,
                                              Description = x.Description,
                                              DepartmentName = y.Name
                                          }).OrderBy(a=>a.Name).ToList();
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Writer.Write(ex.Message, ex.Source);
                    }

                    if (authorData.Any())
                    {
                        Cache.Set("authors", authorData, GiaoTrinhEPU.Caching.Properties.Settings.Default.CacheTime);
                    }
                }
                return authorData;
            }
            else
            {
                //Get the repository data
                IEnumerable<AuthorModel> authorData = null;

                try
                {
                    using (var db = new ThuVienEPUDataContext())
                    {
                        authorData = (from x in db.Authors
                                     join y in db.Departments
                                     on x.DepartmentId equals y.Id
                                     select new AuthorModel     
                                     {
                                        Id = x.Id,
                                        Name= x.Name,
                                        Description = x.Description,
                                        DepartmentName = y.Name
                                     }).OrderBy(a => a.Name).ToList();

                    }
                }
                catch (Exception ex)
                {
                    Logger.Writer.Write(ex.Message, ex.Source);
                }

                return authorData;
            }
        }
        /// <summary>
        /// Get a Author if we know it's id
        /// </summary>
        /// <param name="id">id of the banner</param>
        /// <returns>
        /// return a banner
        /// </returns>
        public Author GetAuthorById(int id)
        {
            Cache.Invalidate("author-" + id);
            Author authorData = Cache.Get("author-" + id) as Author;
            if (authorData == null)
            {
                try
                {
                    using (var db = new ThuVienEPUDataContext())
                    {
                        authorData = db.Authors.Single(a => a.Id.Equals(id));
                    }
                }
                catch (Exception ex)
                {
                    Logger.Writer.Write(ex.Message, ex.Source);
                }

                if (authorData != null)
                {
                    Cache.Set("author-" + id, authorData, GiaoTrinhEPU.Caching.Properties.Settings.Default.CacheTime);
                }
            }
            return authorData;
        }
        /// <summary>
        /// check name of the author already exist in database 
        /// </summary>
        /// <param name="name"></param>
        /// <returns>
        /// return true if exist, else false
        /// </returns>
        public bool HasNameExisted(string name)
        {
            bool isExisted = false;
            try
            {
                using (var db = new ThuVienEPUDataContext())
                {
                    var list = (from a in db.Authors
                                where a.Name.Equals(name)
                                select a.Id).ToList();
                    isExisted = list.Count > 0;
                }
            }
            catch (Exception ex)
            {
                Logger.Writer.Write(ex.Message, ex.Source);
            }
            return isExisted;
        }

        /// <summary>
        /// check duplication of the banner in case of updating the banner
        /// </summary>
        /// <param name="id"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public bool HasNameDuplicated(int id, string name)
        {
            bool isDuplicated = false;
            try
            {
                using (var db = new ThuVienEPUDataContext())
                {
                    var list = (from a in db.Authors
                                where a.Name.Equals(name)
                                where !a.Id.Equals(id)
                                select a.Id).ToList();
                    isDuplicated = list.Count > 0;
                }
            }
            catch (Exception ex)
            {

                Logger.Writer.Write(ex.Message, ex.Source);
            }
            return isDuplicated;
        }

    }
}
